<template>

  <div class="homeDetail">

    <div class="tabr-nav-title">
       <van-nav-bar
        title="快处上报"
        style="width: 100%; height: 44px"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>

    <div>

      <div class="formList">
         <van-form label-width="6.6em" ref="setp1FormRef"
          > <van-cell-group inset
            > <van-field
              v-model="fromDataSetp1.teamName"
              is-link
              readonly
              name="teamName"
              label="处置班组"
              placeholder="点击选择处置班组"
              :disabled="isGroupLeader"
              required
              :rules="[formRules.required]"
              @click="showPicker.teamName = true"
            /> <van-popup
              v-model:show="showPicker.teamName"
              destroy-on-close
              position="bottom"
              > <van-picker
                :model-value="[fromDataSetp1.teamName]"
                :columns="bzListColumns"
                @confirm="(value) => pickerConfirm(value, 'teamName')"
                @cancel="showPicker.teamName = false"
              /> </van-popup
            > <van-field
              v-model="fromDataSetp1.teamGroupName"
              name="teamGroupName"
              label="班组长姓名"
              placeholder="自动获取"
              readonly
              required
            /> <van-field
              v-model="fromDataSetp1.ifDrill"
              is-link
              readonly
              name="ifDrill"
              label="是否演练"
              placeholder="请选择"
              required
              :rules="[formRules.required]"
              @click="showPicker.ifDrill = true"
            /> <van-popup
              v-model:show="showPicker.ifDrill"
              destroy-on-close
              position="bottom"
              > <van-picker
                :model-value="[fromDataSetp1.ifDrill]"
                :columns="columns"
                @confirm="(value) => pickerConfirm(value, 'ifDrill')"
                @cancel="showPicker.ifDrill = false"
              /> </van-popup
            > <van-field
              v-model="fromDataSetp1.ifPint"
              is-link
              readonly
              name="ifPint"
              label="点位是否在库"
              placeholder="点击选择点位是否在库"
              disabled
              required
              :rules="[formRules.required]"
              @click="showPicker.ifPint = true"
            /> <van-popup
              v-model:show="showPicker.ifPint"
              destroy-on-close
              position="bottom"
              > <van-picker
                :model-value="[fromDataSetp1.ifPint]"
                :columns="columns"
                @confirm="(value) => pickerConfirm(value, 'ifPint')"
                @cancel="showPicker.ifPint = false"
              /> </van-popup
            > <van-field
              v-model="fromDataSetp1.riskPoint"
              name="riskPoint"
              label="点位名称"
              placeholder="自动获取"
              readonly
              required
            /> <van-field
              v-model="fromDataSetp1.riskPointAddress"
              name="riskPointAddress"
              label="详细地址"
              placeholder="自动获取"
              readonly
              required
            /> <van-field
              v-model="fromDataSetp1.accumulatedWaterDepth"
              type="number"
              name="accumulatedWaterDepth"
              label="积水深度"
              placeholder="请输入"
              > <template #button> <span>cm</span> </template> </van-field
            > <!-- required
              :rules="[formRules.required]" --> <van-field
              v-model="fromDataSetp1.accumulatedWaterArea"
              type="number"
              name="accumulatedWaterArea"
              label="积水面积"
              placeholder="请输入"
              > <template #button> <span>m²</span> </template> </van-field
            > <!--  required
              :rules="[formRules.required]" --> <van-field
              v-model="fromDataSetp1.accumulatedWaterStartTime"
              is-link
              readonly
              name="accumulatedWaterStartTime"
              label="积水开始时间"
              placeholder="请选择"
              @click="showPicker.accumulatedWaterStartTime = true"
            /> <!-- required
              :rules="[formRules.required]" --> <van-popup
              v-model:show="showPicker.accumulatedWaterStartTime"
              destroy-on-close
              position="bottom"
              > <van-picker-group
                title="积水开始时间"
                :tabs="['选择日期', '选择时间']"
                @confirm="pickerTimeConfirm('accumulatedWaterStartTime')"
                @cancel="showPicker.accumulatedWaterStartTime = false"
                > <van-date-picker
                  v-model="pickerTimer.accumulatedWaterStartTime.date"
                  :max-date="maxDate"
                /> <van-time-picker
                  v-model="pickerTimer.accumulatedWaterStartTime.time"
                /> </van-picker-group
              > </van-popup
            > <van-field
              v-model="fromDataSetp1.ifDisconnection"
              is-link
              readonly
              name="ifDisconnection"
              label="是否断交"
              placeholder="点击选择是否断交"
              @click="showPicker.ifDisconnection = true"
            /> <!-- required
              :rules="[formRules.required]" --> <van-popup
              v-model:show="showPicker.ifDisconnection"
              destroy-on-close
              position="bottom"
              > <van-picker
                :model-value="[fromDataSetp1.ifDisconnection]"
                :columns="columns"
                @confirm="(value) => pickerConfirm(value, 'ifDisconnection')"
                @cancel="showPicker.ifDisconnection = false"
              /> </van-popup
            > <van-field
              v-if="fromDataSetp1.ifDisconnection == '是'"
              v-model="fromDataSetp1.disconnectionContent"
              name="disconnectionContent"
              label="断交时长"
              placeholder="请输入"
              > <template #button> <span>h</span> </template> </van-field
            > <!--  required
              :rules="[formRules.required]" --> <van-field
              v-model="fromDataSetp1.ifTrouble"
              is-link
              readonly
              name="ifTrouble"
              label="是否受困"
              placeholder="点击选择是否受困"
              @click="showPicker.ifTrouble = true"
            /> <!-- required
              :rules="[formRules.required]" --> <van-popup
              v-model:show="showPicker.ifTrouble"
              destroy-on-close
              position="bottom"
              > <van-picker
                :model-value="[fromDataSetp1.ifTrouble]"
                :columns="columns"
                @confirm="(value) => pickerConfirm(value, 'ifTrouble')"
                @cancel="showPicker.ifTrouble = false"
              /> </van-popup
            > <van-field
              v-if="fromDataSetp1.ifTrouble == '是'"
              v-model="fromDataSetp1.predicamentReasons"
              name="predicamentReasons"
              label="受困情况"
              placeholder="请输入"
            /> <!-- required
              :rules="[formRules.required]" --> <van-field
              v-model="fromDataSetp1.bz"
              name="bz"
              label="备注"
              placeholder="请输入"
            />
            <div class="uploadButton">
               <van-uploader
                v-model="fileList.url"
                :before-read="(file) => beforeRead(file, 'url')"
                :after-read="(file) => afterRead(file, 'url')"
                :max-count="5"
                > <van-button type="primary" size="small"
                  >上传点位照片</van-button
                > </van-uploader
              >
            </div>
             </van-cell-group
          > </van-form
        >
      </div>

      <div class="detailFoot">
         <van-button
          style="flex: 1"
          type="success"
          size="small"
          @click="submitClick"
          >确认上报</van-button
        >
      </div>

    </div>
     <!-- 地图点选 --> <GaoMap
      ref="mapRef"
      :center="mapSetting.center"
      v-on:mapClick="mapClick"
    ></GaoMap
    > <drillDialog ref="drillDialogRef" @get-result="handleResult"></drillDialog
    >
  </div>

</template>

<script setup lang="ts">
  import { ref, reactive, onMounted, watch } from 'vue'
  import { useRouter, useRoute } from 'vue-router'
  import {
    showFailToast,
    showSuccessToast,
    showToast,
    showConfirmDialog,
  } from 'vant'
  import GaoMap from '../../../components/GaoMap.vue'
  import drillDialog from './drillDialog.vue'
  import {
    upload,
    getPointPlus,
    dangerClasses,
    speedinessReport,
    getBzOptions,
  } from '../../../api/index.js'
  import formRules from '../../../utils/formRules.ts'
  import { getCurrentDateTimeArray } from '../../../utils/common.ts'
  import { getUserInfo } from '../../../utils/userInfo.js'
  import moment from 'moment'
  const onClickLeft = () => history.back()
  const router = useRouter()
  const route = useRoute()

  const userInfo = getUserInfo()
  const dateTimeArray = getCurrentDateTimeArray()
  const maxDate = new Date(dateTimeArray[0].join('-'))
  const minDate = new Date(2020, 1, 1)

  // 地图组件
  const mapRef = ref()
  const mapSetting = reactive({
    center: [] as number[],
  })

  const columns = [
    { text: '是', value: '是', labelValue: '1' },
    { text: '否', value: '否', labelValue: '0' },
  ]
  const pointPickerColumns = ref([])
  const bzListColumns = ref([])

  const drillDialogRef = ref()

  // 是否班组长
  const isGroupLeader = ref(false)

  const setp1FormRef = ref()
  // const setp2FormRef = ref()
  const showPicker = reactive<Record<string, boolean>>({
    ifPint: false,
    ifDrill: false,
    riskPoint: false,
    teamName: false,
    accumulatedWaterStartTime: false,
    disconnectionContent: false,
    ifTrouble: false,
  })

  const fromDataSetp1 = reactive({
    ifPint: '是',
    ifDrill: '',
    riskPoint: '',
    riskPointId: '',
    coordx: '',
    coordy: '',
    riskPointAddress: '',
    townCode: '',
    streetName: '',
    bz: '',
    accumulatedWaterDepth: '',
    level: '',
    url: [],
    teamId: '',
    teamName: '',
    teamGroupId: '',
    teamGroupName: '',
    teamGroupPhone: '',

    accumulatedWaterStartTime: '',
    accumulatedWaterArea: '',
    ifDisconnection: '',
    disconnectionContent: '',
    ifTrouble: '',
    predicamentReasons: '',
    disposalMatter: '1,2,3,4,5,6,7,8,9,10',
  })

  const pickerTimer = reactive({
    accumulatedWaterStartTime: {
      date: dateTimeArray[0],
      time: dateTimeArray[1],
    },
  })

  // const pointDetail = ref({
  //   id: '1806596606742552613',
  //   code: null,
  //   name: '海尔路鲁家山路口\r\n（江北区寸滩街道海尔路鲁家山路口）',
  //   cityCode: '500000',
  //   city: '重庆市',
  //   countyCode: '500105',
  //   county: '江北区',
  //   townCode: '500105005',
  //   town: '寸滩街道',
  //   responsibleUnit: '区交通局',
  //   responsibleUnitLevel: null,
  //   longitude: 106.627983,
  //   latitude: 29.622777,
  //   address: '海尔路鲁家山路口（江北区寸滩街道海尔路鲁家山路口）',
  //   status: null,
  //   reportor: null,
  //   reportContact: null,
  //   reportTime: null,
  //   remark: '',
  //   fileIds: '',
  //   sourceType: null,
  //   subSourceType: null,
  //   hourlyRainFall: null,
  //   waterLevelRuler: true,
  //   lot: false,
  //   camera: true,
  //   emergencyMeasure: null,
  //   manageLeader: null,
  //   manageLeaderPhone: null,
  //   rectifResponsible: null,
  //   rectifResponsiblePhone: null,
  //   controlResponsible: '王毓樊',
  //   controlResponsiblePhone: '17784720845',
  //   expert: '白静',
  //   expertId: null,
  //   expertPhone: '13883005687',
  //   pointType: '陡坡接缓坡路段',
  //   pointTypeId: '1914609063963803650',
  //   pointLevel: '有一定风险',
  //   geographicFeature: '陡坡接缓坡路段',
  //   topography: '地势低洼',
  //   stagnantWaterCauseIds: '1918953469759180802,1918953882059264001',
  //   actualHistoricalReproducePeriod: 10,
  //   designHistoricalReproducePeriod: null,
  //   affectRiver: null,
  //   standardActual: null,
  //   catchmentArea: null,
  //   warehouse: null,
  //   deleteFlag: 0,
  //   createTime: null,
  //   updateTime: '2025-07-04T08:36:17.062+00:00',
  //   version: 1,
  //   initStarter: true,
  //   focusType: '1',
  //   riskType: '历史风险',
  //   hydropsCnt: 0,
  //   stagnantWaterCause: '施工破坏既有排水系统/杂物堵塞雨水口',
  //   realLineYear: '5',
  //   realNlYear: '100',
  //   standNlYear: '100',
  //   centerResponsible: '朱贞臻、王炜',
  //   lastJstime: null,
  //   djCnt: 0,
  //   djjsHour: '118.9mm/3h（10年）',
  //   hydropsDeep: null,
  //   bz: '为缓解该处积水，江北区在该处实施顶管工程，新增管道20余米',
  //   jyl: null,
  //   drk: '0',
  //   jnJsd: '0',
  //   jnJscs: 0,
  //   nameOther: '江北区寸滩街道海尔路鲁家山路口',
  //   lastHydropstime: '2024-05-25--2024-05-26',
  //   recognizeStatus: null,
  //   refundLibraryExamine: null,
  //   cspsflaqResponsible: '1925230399097585665',
  //   csnlzlResponsible: '1925228365833224194',
  //   ghdwResponsible: '1934868539919810562',
  //   zzResponsible: null,
  //   zzResponsibleId: null,
  //   sdzdResponsible: '1934867926477684738',
  //   zxmbr: null,
  //   zxmbrId: null,
  //   sjResponsible: null,
  //   sjResponsibleId: null,
  //   zxmbrPhone: null,
  //   sjResponsiblePhone: null,
  //   cspsflaqResponsibleName: '楚斌',
  //   csnlzlResponsibleName: '刘波',
  //   ghdwResponsibleName: '刘波',
  //   sdzdResponsibleName: '文华华',
  //   threshold: 101.4,
  //   partition: '中心城区',
  //   pointState: '1',
  //   isShowHandlerBtn: null,
  //   count: null,
  //   isContingencyPlan: '1',
  //   btk: '0',
  //   bcenter: '1',
  //   brisk: '1',
  //   badd: '0',
  //   bzgd: '0',
  //   bgczz: '1',
  // })

  const fileList = ref({
    // 点位照片
    url: [],
  })

  // fromDataSetp1 picker 确认
  const pickerConfirm = ({ selectedValues }, fieldName: string) => {
    showPicker[fieldName] = false
    fromDataSetp1[fieldName] = selectedValues[0]
  }
  // picker 时间选择
  const pickerTimeConfirm = (type: string) => {
    fromDataSetp1[type] =
      pickerTimer[type].date.join('-') +
      ' ' +
      pickerTimer[type].time.join(':') +
      ':00'
    showPicker[type] = false
  }
  // 返回布尔值
  const beforeRead = (file: File | File[], type: string): boolean => {
    const files = Array.isArray(file) ? file : [file]
    const validTypes = ['image/jpeg', 'image/png']
    for (const f of files) {
      if (!validTypes.includes(f.type)) {
        showToast('请上传 jpg/png 格式图片')
        return false
      }
    }

    return true
  }
  // 上传
  const afterRead = (file: any, type: string) => {
    const formData = new FormData()
    formData.append('file', file.file)
    file.status = 'uploading'
    file.message = '上传中...'
    upload(formData).then((res: any) => {
      if (res.data.code === 200 && res.data.data) {
        if (type === 'url') {
          fromDataSetp1[type].push(res.data.data.id)
        }
        file.id = res.data.data.id
        file.status = 'done'
      }
    })
  }

  let obj = {}

  const handleResult = (result) => {
    if (result == '确认') {
      console.log('打印obj', obj)
      speedinessReport(obj)
        .then((res) => {
          if (res.data.code == 200) {
            showSuccessToast('提交成功')
            router.push('/home')
          } else {
            showToast(res.data.message)
          }
        })
        .catch((err) => {
          console.log(err)
          showToast(err.message)
        })
    } else {
    }
  }

  const submitClick = async () => {
    try {
      // 手动触发表单验证
      await setp1FormRef.value.validate()
      if (fromDataSetp1.level === '') {
        fromDataSetp1.accumulatedWaterDepth = '15'
        fromDataSetp1.accumulatedWaterArea = '15'
        fromDataSetp1.level = '3'
        // return showToast('积水深度未达到告警最低等级(15cm)，无需上报')
      }
      if (fromDataSetp1.coordx === '' || fromDataSetp1.coordy === '') {
        history.back()
        // return showToast('请选择地图定位')
      }
      if (fileList.value.url.length === 0) return showToast('请上传点位照片')

      const url = fileList.value.url.map((item) => item.id)

      const ifDisconnection = fromDataSetp1.ifDisconnection === '是' ? 1 : 0
      const ifTrouble = fromDataSetp1.ifTrouble === '是' ? 1 : 0

      obj = {}

      obj = {
        ...fromDataSetp1,
        ifDisconnection,
        disconnectionContent:
          ifDisconnection === 1 ? fromDataSetp1.disconnectionContent : '',
        ifTrouble,
        predicamentReasons:
          ifTrouble === 1 ? fromDataSetp1.predicamentReasons : '',
        url: url.join(','),
      }

      if (fromDataSetp1.ifDrill == '否') {
        drillDialogRef.value.open()
      } else {
        speedinessReport(obj)
          .then((res) => {
            if (res.data.code == 200) {
              showSuccessToast('提交成功')
              router.push('/home')
            } else {
              showToast(res.data.message)
            }
          })
          .catch((err) => {
            console.log(err)
            showToast(err.message)
          })
      }
    } catch (error) {}
  }

  // 地图点击回调
  const mapClick = (e: number[]) => {
    if (!e[0] || !e[1]) return
    fromDataSetp1.coordx = String(e[0])
    fromDataSetp1.coordy = String(e[1])
  }

  // const mapClickOpen = () => {
  //   if (fromDataSetp1.coordx !== '' && fromDataSetp1.coordy !== '') {
  //     mapSetting.center = [
  //       Number(fromDataSetp1.coordx),
  //       Number(fromDataSetp1.coordy),
  //     ]
  //   }
  //   mapRef.value.open()
  // }

  onMounted(async () => {
    const localValue = localStorage.getItem('mapChosePoint')
    if (localValue) {
      const mapChosePoint = JSON.parse(localValue)
      if (mapChosePoint) {
        // console.log('mapChosePoint', mapChosePoint)
        fromDataSetp1.ifPint = mapChosePoint.ifPint
        fromDataSetp1.riskPoint = mapChosePoint.riskPoint
        fromDataSetp1.riskPointId = mapChosePoint.riskPointId
        fromDataSetp1.riskPointAddress = mapChosePoint.riskPointAddress
        fromDataSetp1.townCode = mapChosePoint.townCode
        fromDataSetp1.streetName = mapChosePoint.town
        fromDataSetp1.coordx = mapChosePoint.coordx
        fromDataSetp1.coordy = mapChosePoint.coordy

        // console.log('fromDataSetp1', fromDataSetp1)
      }
    }

    // 积水开始时间默认当前时间
    const nowTime = moment().format('YYYY-MM-DD HH:mm:ss')
    fromDataSetp1.accumulatedWaterStartTime = nowTime

    const { data } = await getBzOptions({
      code: userInfo.countyCode,
    })
    bzListColumns.value =
      data?.data?.map((item) => {
        return {
          ...item,
          text: item.name + `(${item.userName})`,
          value: item.name,
        }
      }) ?? []

    const userId = userInfo.id
    if (bzListColumns.value && bzListColumns.value.length) {
      const list = bzListColumns.value.filter((item) => item.userId == userId)
      if (list && list.length) {
        fromDataSetp1.teamName = list[0].name
        isGroupLeader.value = true
      }
    }
  })

  // 班组
  watch(
    () => fromDataSetp1.teamName,
    (newValue) => {
      const currentBz = bzListColumns.value.find(
        (item) => item.name === newValue,
      )
      fromDataSetp1.teamId = currentBz?.id || ''
      fromDataSetp1.teamGroupId = currentBz?.userId || ''
      fromDataSetp1.teamGroupName = currentBz?.userName || ''
      fromDataSetp1.teamGroupPhone = currentBz?.phone || ''
    },
  )

  // 是否演练
  watch(
    () => fromDataSetp1.ifDrill,
    (newValue) => {
      console.log('是否演练', newValue)
      if (newValue == '否') {
      }
    },
  )

  // 积水深度
  watch(
    () => fromDataSetp1.accumulatedWaterDepth,
    (newValue) => {
      if (Number(newValue) > 50) {
        fromDataSetp1.level = '1'
      } else if (Number(newValue) <= 50 && Number(newValue) > 25) {
        fromDataSetp1.level = '2'
      } else if (Number(newValue) >= 15 && Number(newValue) <= 25) {
        fromDataSetp1.level = '3'
      } else {
        fromDataSetp1.level = ''
      }
    },
  )
</script>

<style scoped lang="less">
  .map-button {
  padding: var(--van-cell-vertical-padding) var(--van-cell-horizontal-padding)
}
.homeDetail {
  height: 100vh;
  background: #f7f8f7;
}

.homeHeader {
  padding: 10px;
  background: #fff;
  margin: 10px 0;
  display: flex;
  justify-content: space-between;
}

.tabr-nav-title {
  display: flex;
  align-items: center;
  font-weight: 600;
  height: 44px;
  font-size: 18px;
  color: #29292c;
  text-align: center;
  font-style: normal;
  background: #fff;
  width: 100vw;
}
.formList {
  height: calc(100vh - 135px);
  margin: 10px 0;
  overflow-y: auto;
  background: #fff;
  .uploadButton {
    padding: 10px;
    box-sizing: border-box;
    :deep(.van-uploader) {
      width: 100%;
      .van-uploader__input-wrapper {
        width: 100%;
        .van-button {
          width: 100%;
        }
      }
    }
  }
  .newList {
    background: #fff;
    border-radius: 10px;
    padding-bottom: 1px;
    margin-bottom: 10px;
    padding: 10px;

    .list {
      width: 100%;
      background-color: rgba(242, 242, 242, 1);
      margin-bottom: 5px;
      padding: 8px 10px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      &:last-child {
        margin-bottom: 0;
      }
      .top {
        color: #333;
        width: calc(100% - 50px);
      }
      .bottom {
        margin-top: 5px;
        --van-switch-width: calc(100vw - 72px);
        position: relative;
        .tips {
          position: absolute;
          bottom: 10px;
          left: 40px;
          .tip {
            margin-left: 50px;
            font-size: 10px;
          }
        }
      }
    }
  }
}
.detailFoot {
  width: 100vw;
  padding: 20px;
  background: #fff;
  position: fixed;
  bottom: 0px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
</style>

